"""
多线程程序

被多个线程竞争的资源（对象）通常称之为临界资源，如果对临界资源没有任何保护措施，
就有可能导致数据状态的错乱，可以通过加锁的方式对临界资源进行保护
"""
import time
from threading import Thread, RLock


class Account:
    """银行账户"""

    def __init__(self):
        self.balance = 0
        self.lock = RLock()

    def deposit(self, money):
        """存钱"""
        with self.lock:
            new_balance = self.balance + money
            time.sleep(0.01)
            self.balance = new_balance

    def withdraw(self, money):
        """取钱"""
        if self.balance >= money:
            with self.lock:
                new_balance = self.balance - money
                time.sleep(0.01)
                self.balance = new_balance
            return True
        return False


account = Account()
threads = []
for _ in range(100):
    t = Thread(target=account.deposit, args=(1, ))
    threads.append(t)
    t.start()
for t in threads:
    t.join()
print(account.balance)
